package com.file.parser;

import com.file.bo.AppAlipayIdCard;
import com.file.bo.AppAlipayJieBei;
import com.file.bo.AppAlipayPersonal;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 支付宝借呗xml解析
 * @author anyspa
 */


@Slf4j
public class AppAlipayJieBeiXmlParser extends AppAlipayBaseXmlParser {

    public ResponseData<String> parseAppAlipayJieBeiXmlToJson(String daId, String filePath, List<String> jiebeiNoDataScenarioList) {
        log.info("parseAppAlipayJieBeiXmlToJson started, daId:{}, filePath:{}", daId, filePath);
        String json = null;

        try {
            if (filePath.contains("alipay_jiebei") || filePath.contains("alipay_quota-jiebei")) {
                AppAlipayJieBei appAlipayJieBei = parseAppAlipayJieBeiXml(daId, filePath, jiebeiNoDataScenarioList);
                json = JsonUtils.convertObjectToJson(appAlipayJieBei);
            } else if (filePath.contains("alipay_personal")) {
                AppAlipayPersonal appAlipayPersonal = parseAppAlipayPersonalXml(filePath);
                json = JsonUtils.convertObjectToJson(appAlipayPersonal);
            } else if (filePath.contains("alipay_idcard")) {
                AppAlipayIdCard appAlipayIdCard = parseAppAlipayIdcardXml(filePath);
                json = JsonUtils.convertObjectToJson(appAlipayIdCard);
            } else {
                throw new RuntimeException("the file name is not supported");
            }
        } catch (Exception e) {
            log.error("|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAppAlipayJieBeiXmlToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseAppAlipayJieBeiXmlToJson completed, daId:{}, filePath:{}", daId, filePath);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private AppAlipayJieBei processNoDataCase(String jiebeiNoDataKeyword) {
        AppAlipayJieBei appAlipayJieBei = new AppAlipayJieBei();
        appAlipayJieBei.setCaseDesc(jiebeiNoDataKeyword);
        return appAlipayJieBei;
    }

    private AppAlipayJieBei processOverDueCase(List<String> nodeTextList) {
        AppAlipayJieBei appAlipayJieBei = new AppAlipayJieBei();
        for (String nodeText : nodeTextList) {
            // 总额度 42,400.00
            if (nodeText.trim().contains("总额度") && nodeText.trim().length() > 3) {
                Pattern pattern = Pattern.compile("([0-9]{1,3}(,[0-9]{3})*)(.[0-9]{2})");
                Matcher matcher = pattern.matcher(nodeText.trim());
                if (matcher.find() && StringUtils.isBlank(appAlipayJieBei.getOverdueAmt())) {
                    appAlipayJieBei.setTotalAmount(matcher.group());
                }
            }
            //  逾期应还338.80
            if (nodeText.trim().contains("逾期应还") && nodeText.trim().length() > 4) {
                Pattern pattern = Pattern.compile("([0-9]{1,3}(,[0-9]{3})*)(.[0-9]{2})");
                Matcher matcher = pattern.matcher(nodeText.trim());
                if (matcher.find() && StringUtils.isBlank(appAlipayJieBei.getOverdueAmt())) {
                    appAlipayJieBei.setOverdueAmt(matcher.group());
                }
            }
        }

        appAlipayJieBei.setCaseDesc("你已逾期");
        return appAlipayJieBei;
    }

    private AppAlipayJieBei processNormalCase(List<String> nodeTextList) {
        AppAlipayJieBei appAlipayJieBei = new AppAlipayJieBei();

        // for循环是否遍历到 "年利率"
        boolean isArrivedAnnualInterestRate = false;
        //正常case里有一种占绝大比例的的有数据case
        for (String nodeText : nodeTextList) {
            if (StringUtils.isNotBlank(nodeText)) {
                if (nodeText.contains("你可以借")) {
                    continue;
                }
                if (!isArrivedAnnualInterestRate && nodeText.contains("年利率")) {
                    isArrivedAnnualInterestRate = true;
                    continue;
                }

                // 可借额度 40,000
                Pattern pattern = Pattern.compile("([0-9]{1,3}(,[0-9]{3})*(?!\\.))|额度已用完");
                Matcher matcher = pattern.matcher(nodeText.trim());
                if (matcher.find() && StringUtils.isBlank(appAlipayJieBei.getBorrowableAmount())) {
                    if (matcher.group().equals("额度已用完")) {
                        appAlipayJieBei.setBorrowableAmount("0");
                        appAlipayJieBei.setCaseDesc("额度已用完");
                    } else {
                        appAlipayJieBei.setBorrowableAmount(matcher.group());
                    }
                    continue;
                }

                if (isArrivedAnnualInterestRate) {
                    // 年利率可能没有小数, 可能有1、2、3位小数,  12.775
                    pattern = Pattern.compile("([0-9]{1,2}(.[0-9]{1,3})?)");
                    matcher = pattern.matcher(nodeText.trim());
                    if (matcher.find() && StringUtils.isBlank(appAlipayJieBei.getAnnualInterestRate())) {
                        appAlipayJieBei.setAnnualInterestRate(matcher.group().concat("%"));
                        continue;
                    }
                }

                // 总额度 40,000.00
                if (nodeText.contains("总额度") || nodeText.contains("总计")) {
                    if (StringUtils.isBlank(appAlipayJieBei.getTotalAmount())) {   //NOSONAR
                        pattern = Pattern.compile("([0-9]{1,3}(,[0-9]{3})*)(.[0-9]{2})");
                        matcher = pattern.matcher(nodeText.trim());
                        if (matcher.find() && StringUtils.isBlank(appAlipayJieBei.getTotalAmount())) {
                            appAlipayJieBei.setTotalAmount(matcher.group());
                        }
                    }
                }
            }
        }
        if (StringUtils.isBlank(appAlipayJieBei.getBorrowableAmount())) {
            throw new RuntimeException("the parsed field has empty value");
        }

        return appAlipayJieBei;
    }

    private AppAlipayJieBei parseAppAlipayJieBeiXml(String daId, String filePath, List<String> jiebeiNoDataScenarioList) throws DocumentException {
        AppAlipayJieBei appAlipayJieBei = null;
        List<String> nodeTextList = getNodeTextList(filePath);
        String jiebeiNoDataKeyword = getNoDataKeyWord(nodeTextList, jiebeiNoDataScenarioList);

        //有数据的正常页面，走正常设值逻辑
        if (isNormalCase(nodeTextList)) {
            appAlipayJieBei = processNormalCase(nodeTextList);
        //有数据的逾期案例，走逾期设值逻辑
        } else if (isOverdue(nodeTextList)) {
            appAlipayJieBei = processOverDueCase(nodeTextList);
        //命中无数据关键字配置，走无数据设值逻辑
        } else if (StringUtils.isNotBlank(jiebeiNoDataKeyword)) {
            appAlipayJieBei = processNoDataCase(jiebeiNoDataKeyword);
        //一些非正常页面，将已知case逐个在这里适配
        } else {
             throw new RuntimeException("jibei xml meet new case");
        }

        return appAlipayJieBei;
    }

    private boolean isOverdue(List<String> nodeTextList) {
        for (String nodeText : nodeTextList) {
            if (nodeText.contains("你已逾期")) {
                return true;
            }
        }
        return false;
    }

    //xml原文件同时包含可用额度和年利率和总额度视为正常case
    private boolean isNormalCase(List<String> nodeTextList) {
        boolean hasBorrowableAmount = false;

        for (String nodeText : nodeTextList) {
            if (nodeText.contains("你可以借") || nodeText.contains("额度已用完")) {
                hasBorrowableAmount = true;
            }
        }
        return hasBorrowableAmount;
    }

    public static void main(String[] args) {
        AppAlipayJieBeiXmlParser appAlipayJieBeiXmlParser = new AppAlipayJieBeiXmlParser();
        List<String> jiebeiNoDataScenarioList = Arrays.asList("借呗服务未开通到你", "暂时无法向你提供借款服务", "你当前登录的账号暂无申请资格", "服务未开通到你", "服务暂未开放到你", "建议多使用支付宝", "你当前暂无借呗额度");
        String json = appAlipayJieBeiXmlParser.parseAppAlipayJieBeiXmlToJson("zd47kptt1747061234612842496", "C:\\Users\\xxx\\Downloads\\zd2qrnk81791399044102787072_35442cee2be712823fad7b5ab6024ea3_alipay_jiebei.xml", jiebeiNoDataScenarioList).getData();
        System.out.println(json);

    }
}
